package com.huijie.app.util;

import com.huijie.app.u.entity.Token;
import com.huijie.app.u.service.ITokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName TokenUtil
 * @Description token工具类
 * @Author Alex
 * @Date 2018/7/20 19:45
 * @Version 1.0
 */
@Component
public class TokenUtil {

    /**
     * request中attribute标识
     */
    public static final String TOKEN_ATTRITUBE = "token";

    /**
     * JWT token 过期时间，单位毫秒，默认7小时
     */
    public static Long JWT_PERIOD = 7 * 3600 * 1000L;


	/**
	 * 秘钥
	 */
	public final static String SECRET_KEY = "ofaffadfev1234567--090swctewst";

	@Autowired
    @Lazy
    private ITokenService tokenService;
	
	public static TokenUtil tokenUtil;

	@PostConstruct
    public void init() {
        tokenUtil = this;
	}
	
	public static Token getToken(String tokenId) {
		return tokenUtil.tokenService.getTokenByTokenId(tokenId);
	}

	public static boolean modify(Token token) {
		return tokenUtil.tokenService.modify(token);
	}

	public static boolean modifySync(Token token) {
		return tokenUtil.tokenService.modifySync(token);
	}

	public static boolean delete(Token token) {
		return tokenUtil.tokenService.deleteHard(token);
	}

	public static Long getJwtPeriod() {
		return JWT_PERIOD;
	}

	public static Token getToken(HttpServletRequest request) {
		return (Token) request.getAttribute(TOKEN_ATTRITUBE);
	}

	public static String getUserLoginName(HttpServletRequest request) {
		Token token = getToken(request);
		return null == token ? null : token.getAppId();
	}

	public static Integer getUserId(HttpServletRequest request) {
		Token token = getToken(request);
		return null == token ? null : token.getUserId();
	}

    public static String getAppId(HttpServletRequest request) {
        Token token = getToken(request);
        return null == token ? null : token.getAppId();
    }

	public static Integer getUserType(HttpServletRequest request) {
		Token token = getToken(request);
		return null == token ? null : token.getUserType();
	}

}
